<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Models\LeapJumpRank;
use App\Http\Models\Item;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class SmallGameController extends Controller
{
    public function list(Request $req)
    {
        $small_game_list = DB::table('small_game_list')->get();
        $result = [];
        if(!empty($small_game_list)) {
            foreach($small_game_list as $info) {
                $result[] = [
                    'icon' => $info['icon'] ?? '',
                    'name' => $info['name'] ?? '',
                    'describe' => $info['content'] ?? '',
                    'url' => $info['url'] ?? '',
                ];
            }
        }
        // 图标   名称  描述   链接
        return $this->result($result);
    }

    public function TreasureCaseProgress (Request $req)
    {
        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');
        // $uinfo = DB::table('users')->where('id', $uid)->first();

        $user_leap_jump = DB::table('user_leap_jump')->where(['user_id'=>$uid])->first();
        if(!isset($user_leap_jump['user_id'])) {
            DB::table('user_leap_jump')->insert([
                'user_id' => $uid,
            ]);
            $user_leap_jump = DB::table('user_leap_jump')->where(['user_id'=>$uid])->first();
        }
        $now = time();
        $today_max_score = 0;
        if($user_leap_jump['receive_time'] < $now ) {
            DB::table('user_leap_jump')->where(['user_id'=>$uid])->update([
                'treasure_status_1' => 0,
                'treasure_status_2' => 0,
                'treasure_status_3' => 0,
                'receive_time' => strtotime("+1 day", strtotime(date('Y-m-d', $now))),
            ]);
            Redis::SET('LeapJumpTodayMaxScore:'.$uid, 0);
        }
        $lear_jump_rewards = DB::table('lear_jump_rewards')->get()->keyBy('id');
        $result = [];
        for($i=1;$i<=3;$i++) {
            if($user_leap_jump['treasure_status_'.$i]) {
                $result[$i] = [
                    'score' => $lear_jump_rewards[$i]['score'],
                    'status' => 1
                ];
            } else {
                $result[$i] = [
                    'score' => $lear_jump_rewards[$i]['score'],
                    'status' => 0
                ];
            }
        }

        $today_max_score = Redis::GET('LeapJumpTodayMaxScore:'.$uid);

        $oneself = LeapJumpRank::getOne( $uid );
        return $this->result([
            'list' => $result,
            'max_score' => $oneself['score'] ?? 0,
            'today_max_score' => $today_max_score ?? 0,
        ]);
    }

    public function finish (Request $req)
    {
        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');
        $uinfo = DB::table('users')->where('id', $uid)->first();
        $score = $req->input('score') ?? 0;

        $user_leap_jump = DB::table('user_leap_jump')->where(['user_id'=>$uid])->first();
        $lear_jump_rewards = DB::table('lear_jump_rewards')->get()->keyBy('id');
        $max_times = 3;
        // 判断宝箱是否可领取
        $returns = [];
        for($i=1;$i<=3;$i++) {
            if($user_leap_jump['treasure_status_'.$i]) {
                $max_times--;
                continue;
            }
            if($score >= $lear_jump_rewards[$i]['score']) {
                $max_times--;
                $all_reward = json_decode($lear_jump_rewards[$i]['rewards'], true);

                // 发放随机奖励
                $total = 0;
                $reward_key = [];
                foreach($all_reward as $key=>$info) {
                    $total += $info['probability'];
                    $reward_key[$key] = $total;
                }
                $random = random_int(0, $total);
                $select_key = null;
                foreach($reward_key as $key=>$val) {
                    if($random <= $val) {
                        $select_key = $key;
                        break;
                    }
                }
                $get_reward = $all_reward[$select_key];
                // 判断是否是优惠券, 先减库存
                if($get_reward['type'] == 3) {
                    $coupon_info = DB::table('lear_jump_coupon')->where(['id'=>$get_reward['id']])->where('inventory','>',0)->first();
                    if(empty($coupon_info)) {
                        unset($get_reward['rewards'][$select_key]);
                        if(!empty($get_reward['rewards'])) {
                            foreach($get_reward['rewards'] as $info) {
                                if($info['type'] == 2) {
                                    $get_reward = $info;
                                }
                            }
                        }
                    } else {
                        DB::statement('update `lear_jump_coupon` set `inventory`=`inventory`-1 where `inventory`>0 and `id`='.$get_reward['id']);
                    }
                }
                $reward = [];
                switch($get_reward['type']) {
                    case 2:
                        $reward[] = ['type'=>config('game.cfg.ItemTypeFodder'), 'num' => $get_reward['nums'], 'id' => config('game.cfg.ItemTypeFodder')];
                        $returns[] = [
                            'type' => 2,
                            'info' => [
                                'add_fodders' => $get_reward['nums'],
                            ],
                        ];
                        break;
                    case 3:
                        $coupon_info = DB::table('lear_jump_coupon')->where(['id'=>$get_reward['id']])->first();
                        if($coupon_info) {
                            $reward[] = ['type'=>config('game.cfg.ItemTypeCoupon'), 'extra' => $coupon_info['batch_number']];
                        }
                        $returns[] = [
                            'type' => 3,
                            'info' => [
                                'name' => $coupon_info['coupon_name'],
                                'total_amount' => $coupon_info['total_amount'],
                                'discount_amount' => $coupon_info['discount_amount'],
                                'jump_url' => $coupon_info['jump_url'],
                            ],
                        ];
                        break;
                }
                Item::give($uid, $reward, $uinfo, 'lear_jump_'.$i);

                DB::table('user_leap_jump')->where(['user_id'=>$uid])->update([
                    'treasure_status_'.$i => 1,
                ]);
            }
        }
        // 判断排行榜是否需要更新
        $user_rank = LeapJumpRank::getOne($uid);
        if($score > $user_rank['score']) {
            LeapJumpRank::set($uid, $score);
            Redis::SET('LeapJumpTodayMaxScore:'.$uid, $score);
        }

        return $this->result([
            'reward' => $returns,
            'remaining_times' => $max_times < 0 ? 0 : $max_times,
        ]);
    }

    public function rank (Request $req)
    {
        $uid = \Auth::user();
        if (!$uid) return $this->throwError('ErrUnAuthorization');
        $uinfo = DB::table('users')->where('id', $uid)->first();
        if(!isset($uinfo['id'])) return $this->throwError('ErrGetUser');

        $lists = LeapJumpRank::gets( 0, 99 );
        // 查询数据
        $result_lists = [];
        if( !empty( $lists ) ) {
            $rank = 1;
            foreach( $lists as $u_id => $score ) {
                $u_info = DB::table('users')->where('id', $u_id)->first();
                if( !isset($u_info['duckId']) ) continue;
                $result_lists[] = [
                    'rank' => $rank++,
                    'nick_name' => $u_info['nickName'] ?? '',
                    'avatar' => $u_info['avatar'] ?? '',
                    'active' => $score ?? 0,
                ];
            }
        }

        $oneself = LeapJumpRank::getOne( $uid );
        return $this->result([
            'list' => $result_lists,
            'oneself' => [
                'rank' => $oneself['index'] ?? 1,
                'nick_name' => $uinfo['nickName'] ?? '',
                'avatar' => $uinfo['avatar'] ?? '',
                'active' => $oneself['score'] ?? 0,
            ],
        ]);
    }
}
